package ExperimentSix.ThreadPool;

import java.util.concurrent.*;

public class CountDownLatchTest {
        public static void main(String[] args) throws InterruptedException {
            int threadCount = 5;
            ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
            final CountDownLatch startSignal = new CountDownLatch(1);
            for (int i = 0; i < threadCount; ++i) {           // 创建线程
                Runnable worker = new Worker(startSignal, "Worker-" + i);
                executorService.execute(worker);
            }
            System.out.println("所有线程准备完毕，一起开始执行...");
            startSignal.countDown(); // 发出开始信号
            executorService.shutdown();
        }

        static class Worker implements Runnable {
            private final CountDownLatch startSignal;
            private final String name;

            Worker(CountDownLatch startSignal, String name) {
                this.startSignal = startSignal;
                this.name = name;
            }

            public void run() {
                try {
                    startSignal.await(); // 等待开始信号
                    System.out.println(name + " 开始执行任务.");
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(ex);
                }
            }
        }
    }